package com.hoyue.dao.impl;

import com.hoyue.bean.Department;
import com.hoyue.dao.DepartmentDao;
import com.hoyue.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class DepartmentDaoImpl implements DepartmentDao {
    QueryRunner qr = C3P0Utils.getQueryRunner();

    @Override
    public void updateDepartment(Department department) throws SQLException {
        String sql = " UPDATE department SET name = ?,introduction = ?,picture_address = ? WHERE id = ? ";

        qr.update(sql, department.getName(), department.getIntroduction(), department.getPicture_address(), department.getId());
    }

    @Override
    public void addDepartment(Department department) throws SQLException {
        String sql = "INSERT INTO department (id,name,introduction,picture_address) VALUES (?,?,?,?)";
        Object[] params = new Object[4];
        params[0] = department.getId();
        params[1] = department.getName();
        params[2] = department.getIntroduction();
        params[3] = department.getPicture_address();

        qr.update(sql, params);
    }

    @Override
    public void deleteDepartment(int id) throws SQLException {
        String sql = "DELETE FROM department where id=?";
        qr.update(sql, id);
    }

    @Override
    public List<Department> getAllList() throws SQLException {
        String sql = " SELECT * FROM department";

        return qr.query(sql, new BeanListHandler<>(Department.class));
    }

    @Override
    public String getAddressById(int id) throws SQLException {
        String sql = "SELECT picture_address FROM department WHERE id=?";

        return qr.query(sql,new ScalarHandler<>(),id);
    }
}
